package tech.abing.spider.task.pageprocessor.amac;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import tech.abing.spider.component.BinaryProcessor;
import tech.abing.spider.request.BinaryRequest;
import tech.abing.spider.task.model.amac.AttachmentEntity;

/**
 * 下载后的附件处理
 * @author Ivan qb.huang@wescxx.com   
 * @date 2016-11-3 下午02:33:59 
 * @version V2.0
 */
public class AttachmentProcessor implements BinaryProcessor {
	
	@Override
	public void process(BinaryRequest binaryRequest, InputStream inputStream) {

		AttachmentEntity attachment = (AttachmentEntity)binaryRequest.getAttribute("attachment");
		
		OutputStream  outputStream = null;
		try {
			File file = new File(attachment.getSavePath());
			if(!file.exists()){
				file.mkdirs();
			}
			
			String fileFullName = attachment.getSavePath()+attachment.getFileName() + "." + attachment.getFileType();
			outputStream = new FileOutputStream(fileFullName);

			int byteCount = 0;
			byte[] bytes = new byte[1024];
			while ((byteCount = inputStream.read(bytes)) != -1){
				outputStream.write(bytes, 0, byteCount);
			}
			
			outputStream.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				inputStream.close();
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	@Override
	public void processError(BinaryRequest binaryRequest) {

	}

}
